const Detail = require('../controllers/base/cosmeticsDetail')
const Classify = require('../modules/base/cosmeticsClassify')
const map = require('../modules/map/classifyFieldMap')
const Op = require('sequelize').Op

let arg = process.argv.splice(2)
let test = arg[0] == '0'
let key = arg[1]
let mapName = arg[2]


start(key)

function start(key) {
    getDetail(`%${key}%`).then(res => {
        handleValue(res, key).then(res => {
            if (test) {
                console.log(res)
            } else {
                res.forEach((value, index) => {
                    map.setMap(`${mapName}_${index}`, value, mapName)
                })
                Classify.addClassify({ classify: key, content: mapName})
            }
        })
    })
}

// handleKey.then(res => {
//     console.log(res)
// })
// 取得所有key值

[
    '商品产地',  '功效',     '色系',
    '国产/进口', '产品产地', '妆效',
    '适用性别',  '类别',     '适合肤质',
    '香调',      '包装',     '规格',
    '适用人群',  '颜色',     '限量款',
    '商品编号',  '店铺',     '商品毛重',
    '货号',      '品牌',     '材质',
    '分类'
  ]

// console.log(handleKey().then(res => {console.log(res)}))
async function handleKey() {
    const data = await Detail.getCosmeticsDetail({})
    // console.log(data)
    let key = new Set()
    for(i of data) {
        let list = JSON.parse(i.classify)
        for(item of list) {
            if (item.key === '商品名称') continue
            key.add(item.key)
        }
    }
    return Array.from(key)
}

// 取得对应key值的所有value
async function handleValue(data, key) {
    let value = new Set()
    for(i of data) {
        let list = JSON.parse(i.classify)
        for(item of list) {
            // if (item. === '商品名称') continue
            if (item.key === key) value.add(item.value)
        }
    }
    if (key === '功效' || key === '适合肤质') {
        let tf = new Set()
        for (str of value) {
            let items = str.split('，')
            for (item of items) {
                tf.add(item)
            }
        }
        value = tf
    }
    return Array.from(value)
}

async function getDetail(sql) {
    let list = await Detail.getCosmeticsDetail({
        classify: {
        [Op.like]: sql
        }
    })
    return list
}

return
